package com.MULY.muly;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

import com.MULY.muly.R;

import android.media.MediaPlayer;
import android.media.MediaPlayer.*;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener  {
	
	private ImageButton playButton ;
	private ImageButton nextButton ;
	private ImageButton previousButton;
	private ImageButton repeatButton ;
	private ImageButton shuffleButton;
	private SeekBar songProgressBar;
	private ImageButton playListButton;
	private TextView songTitleLabel;
	private TextView songCurrentDurationLabel;
	private TextView songTotalDurationLabel;
	private int currentSongIndex = 0;
	
	
	private MediaPlayer mediaPlayer; // to play songs
	private Handler timeHandler = new Handler(); // update time, progress bar. 
	private SongsManager songManager = new SongsManager();
	private Helpers helps = new Helpers();
	
	private boolean isShuffle = false;
	private boolean isRepeat = false;
	
	private ArrayList<HashMap<String,String>> songsList = new ArrayList<HashMap<String, String>>();
	
	
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.musicplayer);
        
        playButton = (ImageButton) findViewById(R.id.btnPlay);
    	nextButton = (ImageButton) findViewById(R.id.btnNext);
    	previousButton = (ImageButton) findViewById(R.id.btnPrevious);
    	repeatButton = (ImageButton) findViewById(R.id.btnRepeat);
    	shuffleButton = (ImageButton) findViewById(R.id.btnShuffle);
    	songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
    	songTitleLabel = (TextView) findViewById(R.id.songTitle);
    	songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
    	songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
    	playListButton = (ImageButton) findViewById(R.id.btnPlaylist);
    	mediaPlayer = new MediaPlayer();
    	
    	//listeners
    	songProgressBar.setOnSeekBarChangeListener(this);
    	mediaPlayer.setOnCompletionListener(this);
    	
    	//getting all the songs
    	songsList = songManager.getPlayList();
    	
    	// play the first song by default    	
    	playSong(0);
    	
    	//playSong button event handler
    	playButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(mediaPlayer.isPlaying()){
					if(mediaPlayer!=null){
						mediaPlayer.pause();
						//change button image to play button
						playButton.setImageResource(R.drawable.img_btn_play);
						
					}else{
						//resume current song
						if(mediaPlayer!=null){
							mediaPlayer.start();
							//change the button into the pause button
							playButton.setImageResource(R.drawable.img_btn_pause);
						}
					}
				}
			}
		});
    	
    	//next button event handler 
    	nextButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//check if there is a next song
				if(currentSongIndex < (songsList.size() -1)){
					playSong(currentSongIndex + 1);
					currentSongIndex += 1;
				}else{
					playSong(0);
					currentSongIndex = 0;
				}
				
			}
		});
    	
    	//previous button event handler
    	previousButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(currentSongIndex > 0){
					playSong(currentSongIndex -1);
					currentSongIndex -=1;
				}else{
					playSong(songsList.size() -1); // play last song
					currentSongIndex = songsList.size() -1;
				}
				
			}
		});
    	
    	//enabling the repeating
    	repeatButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(isRepeat){
					isRepeat = false;
					//let the user know by using a toast
					Toast.makeText(getApplicationContext(), "Repeat is off", Toast.LENGTH_SHORT).show();
					repeatButton.setImageResource(R.drawable.img_btn_repeat);
				}else{
					isRepeat =true;
					Toast.makeText(getApplicationContext(), "Repeat is ON", Toast.LENGTH_SHORT).show();
					//make shuffle to false: this can be changed 
					isShuffle = false;
					repeatButton.setImageResource(R.drawable.img_btn_repeat_pressed);
					shuffleButton.setImageResource(R.drawable.img_btn_shuffle);
				}
				
			}
		});
    	
    	//enabling shuffling
    	shuffleButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(isShuffle){
					isShuffle = false;
					Toast.makeText(getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();
					shuffleButton.setImageResource(R.drawable.img_btn_shuffle);
				}else{
					// make repeat to true
					isShuffle= true;
					Toast.makeText(getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
					// make shuffle to false
					isRepeat = false;
					shuffleButton.setImageResource(R.drawable.img_btn_shuffle_pressed);
					shuffleButton.setImageResource(R.drawable.img_btn_repeat);
				}	
				
			}
		});
    	
    	//playList functionality
    	playListButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(getApplicationContext(),PlayListActivity.class);
				startActivityForResult(i,100);
				
			}
		});
    	
    }
    
    
  //method to play song	
  	public void playSong(int songIndex){
  		
  		try{
  			mediaPlayer.reset();
  			mediaPlayer.setDataSource(songsList.get(songIndex).get("songPath"));
  			mediaPlayer.prepare();
  			mediaPlayer.start();
  			
  			//displaying songTitle
  			String songTitle = songsList.get(songIndex).get("songTitle");
  			songTitleLabel.setText(songTitle);
  			
  			updateProgessBar();
  			
  		}catch(IllegalArgumentException e){
  			e.printStackTrace();
  		}catch(IllegalStateException e){
  			e.printStackTrace();
  		}catch(IOException e){
  			e.printStackTrace();
  		}
  	}

  	//play the song from the songs list
  	public void onActivityResult(int requestCode, int resultCode, Intent data){
  		super.onActivityResult(requestCode, resultCode, data);
  		if(resultCode == 100){
  			currentSongIndex = data.getExtras().getInt("songIndex");
  			//play the selected song
  			playSong(currentSongIndex);
  		}
  	}
  	
  	
  	// method to update the progress bar
	public void updateProgessBar() {
		timeHandler.postDelayed(timeUpdateTimeTask, 100);
		
	}
	
	private Runnable timeUpdateTimeTask = new Runnable(){

		@Override
		public void run() {
			long totalDuration = mediaPlayer.getDuration();
			long currentDuration = mediaPlayer.getCurrentPosition();
			
			//displaying total duration time
			songTotalDurationLabel.setText(""+helps.milliSecondsToTimer(totalDuration));
			
			//displaying time completed playing
			songCurrentDurationLabel.setText(""+helps.milliSecondsToTimer(currentDuration));
			
		}
		
	};

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// remove message Handler from updating progress bar
		timeHandler.removeCallbacks(timeUpdateTimeTask);
		
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		timeHandler.removeCallbacks(timeUpdateTimeTask);
		int totalDuration = mediaPlayer.getDuration();
		int currentPosition = helps.progressToTimer(seekBar.getProgress(), totalDuration);
		
		// forward or backward to certain seconds
		mediaPlayer.seekTo(currentPosition);
		
		// update timer progress again
		updateProgessBar();
		
	}

	@Override
	public void onCompletion(MediaPlayer arg0) {
		
		if(isRepeat){
			playSong(currentSongIndex);
		}else if(isShuffle){
			Random rand = new Random();
			currentSongIndex = rand.nextInt((songsList.size() -1) - 0 + 1) + 0; // wtf
			playSong(currentSongIndex);
		}else{
			if(currentSongIndex < (songsList.size() -1)){
				playSong(currentSongIndex + 1);
				currentSongIndex = currentSongIndex + 1;
			}else{
				playSong(0);
				currentSongIndex = 0;
			}
		}
		
	}

    @Override
    public void onDestroy() {
       super.onDestroy();
       timeHandler.removeCallbacks(timeUpdateTimeTask);
       mediaPlayer.release();
       
    }
    
}
